import java.util.LinkedList;
import java.util.Queue;

public class Main {
    public static void main(String[] args) {
        Solution s = new Solution();
        int i = s.nearestExit(new char[][]{{'+', '+','.', '+'}, {'.', '.', '.','+'}, {'+', '+', '+','.'}}, new int[]{1, 2});
        System.out.println(i);
    }
}
class Solution {
    boolean[][] visited;
    int[] dx = {0, 0, 1, -1};
    int[] dy = {1, -1, 0, 0};
    public int nearestExit(char[][] maze, int[] entrance) {
        int m = maze.length;
        int n = maze[0].length;
        visited = new boolean[m][n];
        int row = entrance[0];
        int col = entrance[1];
        visited[row][col] = true;
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{row, col});
        int steps = 0;
        while(!queue.isEmpty()){
            int sz = queue.size();
            for (int i = 0; i < sz; i++) {
                int[] poll = queue.poll();

                for(int k = 0; k < 4; k++){
                    int x = dx[k] + poll[0];
                    int y = dy[k] + poll[1];

                    if(x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == '.' && !visited[x][y]){

                        //发现相邻节点是出口 返回steps + 1
                        if(x == 0 || x == m - 1 || y == 0 || y == n - 1) return steps + 1;

                        queue.offer(new int[]{x, y});
                        visited[x][y] = true;
                    }
                }
            }
            steps++;
        }
        //说明没有走到边界
        return -1;
    }
}